var api = require('./api_url.js').api
var config = require('./config.js')
var http = require('../http.js')

const NO_VALUE = 11001

function post(url,data,suc_func,err_func) {

  wx.showLoading({
    title: '加载中',
  })

  http.post(url,data).then(function(res) {
    if (typeof suc_func === 'function') {
      suc_func(res)
    }
    wx.hideLoading()
  }).catch(res => {
    console.log(res)
    wx.hideLoading()
    if (typeof err_func === 'function') {
      err_func(res)
    }
  })

  return
  
  wx.showLoading({
    title: '加载中',
  })

  let common_data = { device:'ios',version:'1.1',token: url == api.login ? '' : getToken()};
  data = typeof data === 'object' ? data : {};
  let real_data = {}
  Object.assign(real_data, data, common_data);
 
  wx.request({
    url: url,
    method:'post',
    dataType:'json',
    data: real_data,
    success:function(res) {
      console.log(res)
      res = res.data

      if (!res.hasOwnProperty("code")) {
        errorNotice("服务器错误")
        return
      }

      if (res.code == 401) {
        login()
        errorNotice("登录过期，已重新登录，请再试一次")
        return
      }

      if (res.code == 11001) {
        wx.showModal({
          title: '余额不足',
          content: '前往充值吗',
          success:function(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: config.RECHARGE_PAGE
              })
            }
          }
        })
        return
      }

      if (res.code != 200) {
        errorNotice(res.msg)
        if (res.code == 11001) {
          //TODO
        }
        return
      }
    
      if (typeof suc_func === "function") {
        suc_func(res)
      } else {
         console.log(" post success; " + url)
        console.log("res: ", res)
      }
    },
    fail:function(res) {
      if (typeof err_func === "function") {
        err_func(res)
      } else {
        errorNotice(res.errMsg)
      }
    },
    complete:function() {
      wx.hideLoading()
    }
  })
}

function errorNotice(msg,title) {
  wx.showModal({
    title: title ? title : '操作失败',
    content: msg,
    showCancel:false
  })
}


const TOKEN_KEY = 'token'

function getToken() {
  return wx.getStorageSync(TOKEN_KEY)
}

function login() {
  let code = wx.getStorageSync('code', code)
  post(api.login, {
    data: JSON.stringify({
      code: code,
      invite: '0'
    })
  }, function (res) {
    let token = res.obj.token
    wx.setStorageSync(TOKEN_KEY, token)
  })
}

module.exports = {
  post: post,
  login: login
}
